import axios from "axios";
import { useUserStore } from "@/stores";
import { ElMessage } from "element-plus";
import router from "@/router";

const baseURL = "/api";

// 创建一个axios的实例
const instance = axios.create({
  baseURL,
  timeout: 10000,
});

instance.interceptors.request.use(
  (config) => {
    // const userStore = useUserStore();
    // console.log(userStore, token);

    const token = localStorage.getItem("token");
    if (token) {
      config.headers["Authorization"] =
        "Bearer " + localStorage.getItem("token"); // 确保使用Bearer schema
    }
    return config;
  },
  (err) => Promise.reject(err)
);

instance.interceptors.response.use(
  (res) => {
    // TODO 3. 处理业务失败(code为200表示成功，其他为失败)
    if (res.data && res.data.code === 200) {
      return res;
    }
    ElMessage({ message: res.data?.msg || "服务异常", type: "error" });
    return Promise.reject(res.data);
  },
  (err) => {
    // TODO 5. 处理401错误
    let errorMessage = "服务异常";
    if (err.response && err.response.data) {
      errorMessage = err.response.data.msg || errorMessage;
    }
    ElMessage({ message: "错误：" + errorMessage, type: "error" });
    console.log(err);
    handleAuthError(err);
    return Promise.reject(err);
  }
);

function handleAuthError(err) {
  if (err.response?.status === 401) {
    console.log("请重新登录");
    const userStore = useUserStore();
    userStore.removeToken();
    router.push("/login");
  }
}

export default instance;
export { baseURL };
